package com.example.stgv;

import java.security.MessageDigest;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class DBHelper extends SQLiteOpenHelper {

	// KHAI BAO THONG TIN DATABASE

	private static final String DATABASE_NAME = "DBStudent";
	private static final int DATABASE_VERSION = 7;
	DiemData diemx = new DiemData();
	LopHocsData lopx = new LopHocsData();
	HocSinhData hocsinhx = new HocSinhData();
	PinData pinx = new PinData();
	DiemDanhData ddx = new DiemDanhData();

	Context mycontext;
	// 1./KHAI BAO THONG TIN BANG LOP
	public final String CREATE_TABLE_LOP = "CREATE TABLE "
			+ lopx.getDATABASE_TABLE_LOP() + " ( " + lopx.getKEY_MALOP()
			+ " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
			+ lopx.getKEY_TENLOP() + " nvARCHAR(50) NOT NULL, "
			+ lopx.getKEY_SISO() + " nUMERIC  NOT NULL) ";
	/*
	 * + lopx.getKEY_NAMHOC() + " VARCHAR(9) NOT NULL )";
	 */

	// 2./KHAI BAO THONG TIN BANG HOCSINH
	private final String CREATE_TABLE_HOCSINH = "CREATE TABLE "
			+ hocsinhx.getDATABASE_TABLE_HOCSINH() + " ( "
			+ hocsinhx.getKEY_MAHS()
			+ " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
			+ hocsinhx.getKEY_TENHS() + " nvARCHAR(100)  NOT NULL, "
			+ hocsinhx.getKEY_GIOITINH() + " BOOLEAN  NOT NULL, "
			+ hocsinhx.getKEY_NGAYSINH() + " vARCHAR(10) NOT NULL,"
			+ hocsinhx.getKEY_DIACHI() + " TEXT  NULL, " + lopx.getKEY_MALOP()
			+ " INTEGER NOT NULL CONSTRAINT " + lopx.getKEY_MALOP()
			+ " REFERENCES " + lopx.getDATABASE_TABLE_LOP() + " ( "
			+ lopx.getKEY_MALOP() + " ) ON DELETE CASCADE)";

	// 3./KHAI BAO THONG TIN BANG DIEM
	private final String CREATE_TABLE_DIEM = "CREATE TABLE "
			+ diemx.getDATABASE_TABLE_DIEM() + " ( " + hocsinhx.getKEY_MAHS()
			+ " INTEGER  NOT NULL , " + diemx.getKEY_LOAIDIEM()
			+ " vARCHAR(10)  NOT NULL , " + lopx.getKEY_MALOP()
			+ " INTEGER  NOT NULL , " + diemx.getKEY_DIEM()
			+ " fLOAT  NOT NULL )";

	// 4./KHAI BAO THONG TIN BANG DIEM
	private final String CREATE_TABLE_PIN = "CREATE TABLE "
			+ pinx.getDATABASE_TABLE_PIN() + " ( " + pinx.getKEY_MAPIN()
			+ " vARCHAR(10)  NOT NULL)";

	// 5./KHAI BAO THONG TIN BANG DIEM
	private final String CREATE_TABLE_DIEMDANH = "CREATE TABLE "
			+ ddx.getDATABASE_TABLE_DIEMDANH() + " ( " + hocsinhx.getKEY_MAHS()
			+ " INTEGER  NOT NULL , " + ddx.getKEY_LOAIDD()
			+ " vARCHAR(10)  NOT NULL , " + ddx.getKEY_NGAY()
			+ " INTEGER  NOT NULL )";

	public DBHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		Log.d("Database Helper", "Database Open!!!!!!");

	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		try {
			db.execSQL(CREATE_TABLE_LOP);
			Log.d("onCreate ", "Table Lop Create!!!!!!");
			db.execSQL(CREATE_TABLE_HOCSINH);
			Log.d("onCreate ", "Table HocSinh Create!!!!!!");
			db.execSQL(CREATE_TABLE_DIEM);
			Log.d("onCreate ", "Table Diem Create!!!!!!");
			db.execSQL(CREATE_TABLE_PIN);
			Log.d("onCreate ", "Table PIN Create!!!!!!");
			db.execSQL(CREATE_TABLE_DIEMDANH);
			Log.d("onCreate ", "Table Diem Danh Create!!!!!!");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		try {
			// TODO Auto-generated method stub
			db.execSQL("DROP TABLE IF EXISTS " + lopx.getDATABASE_TABLE_LOP());
			db.execSQL("DROP TABLE IF EXISTS "
					+ hocsinhx.getDATABASE_TABLE_HOCSINH());
			db.execSQL("DROP TABLE IF EXISTS " + diemx.getDATABASE_TABLE_DIEM());
			db.execSQL("DROP TABLE IF EXISTS " + pinx.getDATABASE_TABLE_PIN());
			db.execSQL("DROP TABLE IF EXISTS "
					+ ddx.getDATABASE_TABLE_DIEMDANH());
			onCreate(db);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public long insertData(String table, Integer agr, String[] fields,
			String[] values) {
		Log.d("Thong bao", " Insert Bang ");
		try {
			SQLiteDatabase mDB = this.getWritableDatabase();
			ContentValues cv = new ContentValues();
			for (int i = 0; i < agr; i++) {
				cv.put(fields[i], values[i]);
			}
			Log.d("Insert", "Bang " + table + " noi dung " + cv);
			return mDB.insert(table, null, cv);
		} catch (Exception e) {
			Log.d("Insert", "Khong the insert. " + e);
			return -1;
		}
	}

	public long UpdateData(String table, Integer agr, String[] fields,
			String[] values, String whereClause, String[] whereArgs) {
		Log.d("Thong bao", "Update Bang ");
		try {
			SQLiteDatabase mDB = this.getWritableDatabase();
			ContentValues cv = new ContentValues();
			for (int i = 0; i < agr; i++) {
				cv.put(fields[i], values[i]);
			}
			Log.d("Update", "Bang " + table + " noi dung " + cv);
			return mDB.update(table, cv, whereClause, whereArgs);

		} catch (Exception e) {
			Log.d("Update", "Khong the update. " + e);
			return -1;
		}
	}

	public Cursor getAllData(String table, String[] columns, String selection,
			String[] selectionArgs, String groupBy, String having,
			String orderBy) {
		SQLiteDatabase mDB = this.getReadableDatabase();
		ContentValues cv = new ContentValues();
		Log.d("thong bao", "Bang " + table + " noi dung " + cv);
		return mDB.query(table, columns, selection, selectionArgs, groupBy,
				having, orderBy);
	}

	public Cursor getAllData(String table) {
		SQLiteDatabase mDB = this.getReadableDatabase();
		ContentValues cv = new ContentValues();
		Log.d("thong bao", "Bang " + table + " noi dung " + cv);
		return mDB.query(table, null, null, null, null, null, null);
	}

	public Cursor getAllData(String table, String orderBy) {
		SQLiteDatabase mDB = this.getReadableDatabase();
		ContentValues cv = new ContentValues();
		Log.d("thong bao", "Bang " + table + " noi dung " + cv);
		return mDB.query(table, null, null, null, null, null, orderBy);
	}

	public Cursor runAllDateRQ(String sql) {
		SQLiteDatabase mDB = this.getReadableDatabase();
		Log.d("Running.", "Running Raw Query.");
		return mDB.rawQuery(sql, null);
	}

	public Cursor runAllDateRQ(String sql, String[] value) {
		SQLiteDatabase mDB = this.getReadableDatabase();
		Log.d("Running.", "Running Raw Query.");
		return mDB.rawQuery(sql, value);
	}

	public long deleteData(String table, String sql, String[] whereArgs) {
		SQLiteDatabase mDB = this.getReadableDatabase();
		Log.d("Running.", "Running Raw Query.");
		return mDB.delete(table, sql, whereArgs);
	}

	// Ma hoa MD5
	public String convertMD5(String chuoi) throws Exception {
		StringBuffer hexString = new StringBuffer();
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(chuoi.getBytes());
		byte[] mdbytes = md.digest();
		for (int i = 0; i < mdbytes.length; i++) {
			String hex = Integer.toHexString(0xff & mdbytes[i]);
			if (hex.length() == 1)
				hexString.append('0');
			hexString.append(hex);
		}
		Log.d("Log", "Chuoi sau khi doi: " + hexString);
		return hexString.toString();
	}

	public Boolean insertDiemDanh(String idhs, String loaiDD, String ngay) {

		try {
			SQLiteDatabase mDB = this.getReadableDatabase();
			int nParam = 3;
			String[] fields = new String[nParam];
			String[] values = new String[nParam];
			String[] whereArgs = new String[2];

			fields[0] = ddx.getKEY_MAHS();
			fields[1] = ddx.getKEY_NGAY();
			fields[2] = ddx.getKEY_LOAIDD();

			values[0] = idhs;
			values[1] = ngay;
			values[2] = loaiDD;

			whereArgs[0] = idhs;
			whereArgs[1] = ngay;

			String sql = "select mahs form diemdanh where mahs=? and ngay=?";
			Cursor cur = runAllDateRQ(sql, whereArgs);
			if (cur != null && cur.getCount() > 0) {
				return false;
			} else {
				insertData(ddx.getDATABASE_TABLE_DIEMDANH(), nParam,
						fields, values);
				return true;
			}

		} catch (Exception e) {

		}
		return false;
	}

}
